﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;

namespace Cache.FileCache
{
    /// <summary>
    /// 文件缓存配置节
    /// </summary>
    public class FileCachedSection
    {
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <returns></returns>
        public static FileCachedConfig GetConfig()
        {
            XmlNode section = ConfigurationManager.GetSection("Cache") as XmlNode;
            if (section == null)
            {
                return null;
            }

            foreach (XmlNode child in section.ChildNodes)
            {
                if (child.Name.ToLower() == "filecached")
                {
                    return ParseConfig(child);
                }
            }
            return null;
        }

        private static FileCachedConfig ParseConfig(XmlNode section)
        {
            FileCachedConfig config = new FileCachedConfig();
            foreach (XmlNode child in section.ChildNodes)
            {
                if (child.Name.ToLower() == "setting")
                {
                    if (child.Attributes["IsCache"] != null)
                    {
                        config.IsCache = bool.Parse(child.Attributes["IsCache"].Value);
                    }
                }
                else if (child.Name.ToLower() == "add")
                {
                    FileCachedNode node = new FileCachedNode();
                    if (child.Attributes["name"] != null)
                    {
                        node.Name = child.Attributes["name"].Value;
                    }
                    if (child.Attributes["FileCachePath"] != null)
                    {
                        node.FileCachePath = child.Attributes["FileCachePath"].Value;
                    }
                    if (child.Attributes["KeyPrefix"] != null)
                    {
                        node.KeyPrefix = child.Attributes["KeyPrefix"].Value;
                    }
                    if (child.Attributes["CacheSubDirs"] != null)
                    {
                        node.CacheSubDirs = int.Parse(child.Attributes["CacheSubDirs"].Value);
                    }
                    config.Nodes.Add(node.Name,node);
                }
            }
            return config;
        }
    }
}
